package me.hgj.jetpackmvvm.ledun.ui.fragment.me

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log

import me.hgj.jetpackmvvm.ledun.app.util.CacheUtil
import java.util.Calendar

class AlarmReceiver: BroadcastReceiver() {


    override fun onReceive(context: Context, intent: Intent) {
        when (intent.action) {
            "MORNING_ALARM" -> {
                // 早上 8 点执行的操作

                // 重新设置下一个闹钟

                setNextDayMorningAlarm(context,true)
            }

            "EVENING_ALARM" -> {
                // 晚上 6 点执行的操作
                Log.e("laiywien", "onReceive:=====even " )

                setNextDayMorningAlarm(context,false)
            }
        }
    }

    private fun setNextDayMorningAlarm(context: Context,isMorning:Boolean) {
        val intent = Intent(context, AlarmReceiver::class.java)
        if (isMorning){
            intent.action = "MORNING_ALARM"
        }else
        {
            intent.action = "EVENING_ALARM"
        }


        // 获取当前时间，并设置为明天的当前时间
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.DAY_OF_YEAR, 1)
        if (isMorning){
            calendar.set(Calendar.HOUR_OF_DAY, CacheUtil.getRiseHour())
            calendar.set(Calendar.MINUTE, CacheUtil.getRiseMunite())
        }else{
            calendar.set(Calendar.HOUR_OF_DAY, CacheUtil.getHour())
            calendar.set(Calendar.MINUTE, CacheUtil.getMunite())
        }

        calendar.set(Calendar.SECOND, 0)


        val pendingIntent = PendingIntent.getBroadcast(
            context, intent.action.hashCode(), intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )


        printCalendarDate(calendar)
        // 获取AlarmManager服务
        val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

        // 设置精确闹钟
        alarmManager.setExact(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            pendingIntent
        )
    }

    fun printCalendarDate(calendar: Calendar) {
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH) + 1  // Calendar.MONTH 是从0开始的
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)
        val second = calendar.get(Calendar.SECOND)
        Log.e("laiyiwen","Current Date and Time:Year: $year Month: $month Day: $day Hour: $hour Minute: $minute Second: $second")
    }
}